import requests
from bs4 import BeautifulSoup
import yt_dlp

def find_video_links(page_url):
    page_url = "https://shangzhibo.tv/watch/11293779"  # 替换为网页地址

    """
    从网页中提取所有视频链接。
    """
    response = requests.get(page_url)
    if response.status_code != 200:
        print(f"无法访问网页，状态码: {response.status_code}")
        return []

    soup = BeautifulSoup(response.text, "html.parser")
    video_links = []

    # 查找 <video> 标签
    for video in soup.find_all("video"):
        video_src = video.get("src")
        if video_src:
            video_links.append(video_src)

    # 查找嵌入的视频（如 iframe 或其他标签）
    for source in soup.find_all("source"):
        source_src = source.get("src")
        if source_src:
            video_links.append(source_src)

    return video_links


def download_video(video_url, save_path):
    """
    使用 yt-dlp 下载视频。
    """
    ydl_opts = {
        "outtmpl": save_path,  # 保存路径
        "format": "bestvideo+bestaudio/best",  # 选择最佳质量
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([video_url])
    print(f"视频已保存到: {save_path}")


def main():
    # 输入网页 URL
    page_url = "https://example.com/page-with-video"  # 替换为实际网页地址
    print(f"正在解析网页: {page_url}")

    # 获取视频链接
    video_links = find_video_links(page_url)
    if not video_links:
        print("未找到视频链接。")
        return

    print(f"找到以下视频链接: {video_links}")

    # 下载每个视频
    for i, video_url in enumerate(video_links):
        if not video_url.startswith("http"):
            # 如果是相对路径，补全为绝对路径
            video_url = requests.compat.urljoin(page_url, video_url)
        save_path = "../File/downloaded_video.mp4"
        print(f"正在下载视频: {video_url}")
        download_video(video_url, save_path)


if __name__ == "__main__":
    main()

